<template>
    <view class="container">
        <image class="bg-image" src="/static/image.jpg" mode="aspectFill"></image>
        <view class="nav-bar">
            <view class="back-btn" @click="goBack">
                <image src="/static/return.png" mode="aspectFit" class="back-icon"/>
            </view>
            <text class="nav-title">我的单词本</text>
        </view>
        
        <view class="content">
            <view class="card-body">
                <view 
                    class="wordbook-item" 
                    v-for="book in wordbooks" 
                    :key="book.wordbook_id"
                >
                    <image 
                        :src="'/static/' + getRandomBookCover()" 
                        mode="aspectFill" 
                        class="book-cover"
                    />
                    <view class="wordbook-info">
                        <text class="wordbook-title">{{ book.wordbook_name }}</text>
                       
                    </view>
                </view>
            </view>
        </view>
        
        <view class="create-btn" @click="showCreateDialog">
            <text class="create-text">新建单词本</text>
        </view>
    </view>
</template>

<script>
import { user_wordbooks,create } from '@/api/user.js'

export default {
    data() {
        return {
            wordbooks: []
        }
    },
    onShow() {
        this.loadWordbooks()
    },
    methods: {
        getUserIdFromToken() {
            const authorization = uni.getStorageSync('token')
            console.log('原始token:', authorization)
            
            if (!authorization) {
                console.warn('未找到token')
                return null
            }
            
            try {
                // 移除 "Bearer " 前缀
                const token = authorization.replace('Bearer ', '')
                console.log('处理后的token:', token)
                
                // 分割 token，获取第一部分
                const tokenParts = token.split('.')
                console.log('token分割结果:', tokenParts)
                
                if (tokenParts.length > 0) {
                    const userInfo = JSON.parse(tokenParts[0])
                    console.log('解析出的用户信息:', userInfo)
                    return userInfo.id
                }
                console.warn('token格式不正确')
                return null
            } catch (error) {
                console.error('解析token失败:', error)
                return null
            }
        },
        
        async loadWordbooks() {
            try {
                const userId = this.getUserIdFromToken()
                console.log('获取到的用户ID:', userId)
                
                if (!userId) {
                    console.warn('未获取到用户ID')
                    uni.showToast({
                        title: '请先登录',
                        icon: 'none'
                    })
                    return
                }
                
                
                const res = await user_wordbooks({
                    user_id: String(userId)
                })
                
                console.log('获取单词本响应：', res)
                if (res.code === '2000') {
                    this.wordbooks = res.data
                } else {
                    uni.showToast({
                        title: res.message || '获取单词本失败',
                        icon: 'none'
                    })
                }
            } catch (error) {
                console.error('获取单词本失败：', error)
                uni.showToast({
                    title: '获取单词本失败，请重试',
                    icon: 'none'
                })
            }
        },
        selectWordbook(book) {
            // TODO: 处理单词本选择
            console.log('选择单词本：', book)
        },
        showCreateDialog() {
            uni.showModal({
                title: '新建单词本',
                editable: true,
                placeholderText: '请输入单词本名称',
                success: async (res) => {
                    if (res.confirm && res.content) {
                        const userId = this.getUserIdFromToken()
                        if (!userId) {
                            uni.showToast({
                                title: '请先登录',
                                icon: 'none'
                            })
                            return
                        }
                        
                        try {
                            const result = await create({
                                user_id: String(userId),
                                wordbook_name: res.content.trim()
                            })
                            
                            console.log('创建单词本响应：', result)
                            
                            if (result.code === '2000') {
                                uni.showToast({
                                    title: '创建成功',
                                    icon: 'success'
                                })
                                // 刷新单词本列表
                                this.loadWordbooks()
                            } else {
                                uni.showToast({
                                    title: result.message || '创建失败',
                                    icon: 'none'
                                })
                            }
                        } catch (error) {
                            console.error('创建单词本失败:', error)
                            uni.showToast({
                                title: '创建失败，请重试',
                                icon: 'none'
                            })
                        }
                    }
                }
            })
        },
        goBack() {
            uni.navigateBack()
        },
        getRandomBookCover() {
            // 随机返回 book3.png 或 book4.png
            return Math.random() < 0.5 ? 'book3.png' : 'book4.png'
        }
    }
}
</script>

<style>
.container {
    width: 100%;
    height: 100vh;
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
}

.bg-image {
    position: fixed;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    z-index: 1;
}

.nav-bar {
    position: relative;
    z-index: 2;
    display: flex;
    align-items: center;
    padding: 40px 20px 20px;
}

.back-icon {
    width: 24px;
    height: 24px;
}

.nav-title {
    flex: 1;
    text-align: center;
    font-size: 18px;
    color: #333;
}

.content {
    position: relative;
    z-index: 2;
    padding: 20px;
}

.card-body {
    background: rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 20px;
}

.wordbook-item {
    background: rgba(255, 255, 255, 0.3);
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 15px;
}


.book-cover {
    width: 60px;
    height: 80px;
    border-radius: 4px;
    object-fit: cover;
}

.wordbook-info {
    flex: 1;
    display: flex;
    flex-direction: column;
}

.wordbook-title {
    font-size: 16px;
    color: #333;
    margin-bottom: 8px;
    font-weight: 500;
}

.wordbook-count {
    font-size: 12px;
    color: #666;
}

.create-btn {
    position: fixed;
    bottom: 30px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(107, 75, 138, 0.9);
    backdrop-filter: blur(5px);
    padding: 12px 30px;
    border-radius: 24px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    z-index: 100;
}

.create-text {
    color: #fff;
    font-size: 16px;
    font-weight: 500;
}

.create-btn:active {
    opacity: 0.8;
}
</style> 